package org.flashbrighton.as3bots.views.ui.scores
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.*;
	import flash.utils.Dictionary;
	import org.flashbrighton.as3bots.models.BotModel;
	import org.flashbrighton.as3bots.models.GameModel;	
	import org.flashbrighton.as3bots.components.HealthComponent;
	import org.flashbrighton.as3bots.events.DeadBotEvent;

	public class ScoreBoard extends Sprite
	{
		private var _model:GameModel;
		private var _scores:Vector.<BotScore>;
		private var _scoresByModel:Dictionary;
		
		
		public function ScoreBoard(model:GameModel)
		{
			_model = model;
			init();	
			_model.addEventListener(Event.CHANGE, update);
			_model.addEventListener(DeadBotEvent.DEAD, removeScore);
		}
		
		
		private function init():void
		{
			var score:BotScore;
			
			
			_scores = new Vector.<BotScore>();
			_scoresByModel = new Dictionary(true);
			
			for each (var botModel:BotModel in _model.botList) 
			{
				score = new BotScore(botModel);
				_scores.push(score);
				_scoresByModel[botModel] = score;				
				addChild(score);
			}
			
			setPositions();
		}
		
		
		private function update(e:Event):void
		{
			for each (var score:BotScore in _scores) 
			{
				score.update();
			}
		}
		
		
		private function removeScore(e:DeadBotEvent):void 
		{
			var score:BotScore = _scoresByModel[e.botModel];
			removeChild(score);
			_scoresByModel[e.botModel] = null;
			_scores.splice(_scores.indexOf(score), 1);
			setPositions();
		}
		
		
		private function setPositions():void 
		{
			var gapY:int = 5;
			
			for (var i:int = 0; i < _scores.length; i++)
			{
				if (i > 0) _scores[i].y = _scores[i - 1].y + _scores[i - 1].height + gapY;
			}
		}

	}
}